package com.feishi.core.util.ssh;

import com.jcraft.jsch.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Random;

/**
 * @version 1.0
 * @auth caixq
 * @time 18-6-28 16:56
 **/
public class SshUtil {
    public static void main(String[] args) throws JSchException, InterruptedException {


        Session session = createSession("192.168.159.199","linaro","linaro");

        session.connect();
        ChannelExec channel=getChannelExec(session);


       runCmd(channel,"wget http://10.12.16.138/5b234c27c8584d04080d8ef7.mp3 -O /tmp/audio.mp3 && /home/linaro/HMI/play /tmp/audio.mp3");
        runCmd(channel,"wget http://10.12.16.138/5b234c27c8584d04080d8ef7.mp3 -O /tmp/audio.mp3 && /home/linaro/HMI/play /tmp/audio.mp3");

    }

    public static ChannelExec getChannelExec(Session session) throws JSchException {
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        channel.setInputStream(null);
        channel.setErrStream(System.err); // 获取执行错误的信息
        channel.setOutputStream(System.out);
        return channel;
    }
    public static ChannelExec getChannelExec(String host, String userName, String password) throws JSchException {
        ChannelExec channel = (ChannelExec) (createSession(host,userName,password)).openChannel("exec");
        channel.setInputStream(null);
        channel.setErrStream(System.err); // 获取执行错误的信息
        channel.setOutputStream(System.out);
        return channel;
    }

    public static Session createSession(String host, String userName, String password) throws JSchException {

        JSch jsch = new JSch();
        Session session = jsch.getSession(userName,host,22);
        session.setPassword(password);

        Properties props = new Properties();
        props.put("StrictHostKeyChecking", "no");
        session.setConfig(props);
        return session;
    }
    public static void runCmd(ChannelExec channel,String cmd){
        runCmd(channel,cmd,false);
    }
    public static void runCmd(ChannelExec channel,String cmd,boolean isWait){
        try {
            if(channel==null || !channel.getSession().isConnected()){
                System.err.println("无法发送命令，通道未开启");
                return;
            }

            //等待之前命令执行完毕
            while (channel.isConnected()){
                Thread.sleep(20);
            }
            channel.setCommand(cmd);
            channel.connect();
            if(isWait){
                while (!channel.isEOF()){
                    Thread.sleep(20);
                }
            }

        }catch (Exception e){

        }
    }
}
